06. Exercise: Composition
Composition
Composition is a closely related alternative to inheritance. Composition involves constructing ("composing") classes from other classes, instead of inheriting traits from a parent class.
A common way to distinguish "composition" from "inheritance" is to think about what an object can do, rather than what it is. This is often expressed as "has a" versus "is a".
From the standpoint of composition, a cat "has a" head and "has a" set of paws and "has a" tail.
From the standpoint of inheritance, a cat "is a" mammal.
There is no hard and fast rule about when to prefer composition over inheritance. In general, if a class needs only extend a small amount of functionality beyond what is already offered by another class, it makes sense to inherit from that other class. However, if a class needs to contain functionality from a variety of otherwise unrelated classes, it makes sense to compose the class from those other classes.
In this example, you'll practice working with composition in C++.
Instructions
In this exercise, you will start with a LineSegment
class and create a Circle
class.
Note that you will compose Circle
from LineSegment
, instead of inheriting Circle
from LineSegment
. Specifically, the length
attribute from LineSegment
will become the circle's radius.
- Create a class
LineSegment
. - Declare an attribute
length
in classLineSegment
. - Define pi (3.14159) with a
macro
. - Create a class
Circle
, composed of aLineSegment
that represent's the circle's radius. Use this radius to calculate the area of the circle (area of a circle = \pi r^2). - Verify the behavior of
Circle
inmain()
.
Workspace
This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity, so you may be able to download them there.
Workspace Information:
- Default file path:
- Workspace type: jupyter
- Opened files (when workspace is loaded): n/a